package com.bieyang.anjia.ui.activity;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import com.bieyang.anjia.R;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.SubUtils;

import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaRecorder;
import android.media.MediaRecorder.OnErrorListener;
import android.media.MediaRecorder.OnInfoListener;
import android.os.Bundle;
import android.os.Handler;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;

@SuppressLint({ "HandlerLeak", "SimpleDateFormat" })
public class RecorderActivity extends Activity implements
		SurfaceHolder.Callback {
	private int modeCode;
	private File myRecVideoFile;
	private SurfaceView mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	private MediaRecorder recorder;
	private Camera camera;
	private boolean isAlive = false;
	private boolean recording; // 记录是否正在录像,fasle为未录像, true 为正在录像
	private String filePath;
	private int encodingBitRate = 256 * 1024, frameRate = 15;

	Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				recorder();
				break;
			case 1:
				releaseMediaRecorder();
				// 关闭预览并释放资源
				if (camera != null) {
					camera.stopPreview();
					camera.release();
					camera = null;
				}
				if (null != myRecVideoFile && myRecVideoFile.exists()
						&& 0 != myRecVideoFile.length()) {
					Intent data = new Intent();
					data.putExtra(Constants.VIDEO_PATH, filePath);
					setResult(Constants.RECORD_VIDEO_CODE, data);
				}
				RecorderActivity.this.finish();
				break;
			default:
				break;
			}
		};
	};

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_recorder);
		modeCode = getIntent().getIntExtra(Constants.MODE_CODE, 0);
		isAlive = true;
		// 设置sdcard的路径
		String folderPath = new SubUtils()
				.getFileFloderPath(RecorderActivity.this);
		if (null == folderPath) {
			finish();
		}
		String name = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
				+ Constants.VIDEO_SUFFIX;
		filePath = folderPath + name;
		findViewById(R.id.tvBack).setVisibility(
				App.screenStates ? View.VISIBLE : View.GONE);
		mSurfaceView = (SurfaceView) findViewById(R.id.recorder_surface);
		mSurfaceHolder = mSurfaceView.getHolder();
		mSurfaceHolder.addCallback(this);
		mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mSurfaceHolder.setKeepScreenOn(true);

		mSurfaceView.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				recorder();
				return false;
			}
		});
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		// 开启相机
		if (camera == null) {
			camera = Camera.open(0);
			try {
				camera.setPreviewDisplay(mSurfaceHolder);
				camera.startPreview();
			} catch (IOException e) {
				e.printStackTrace();
				camera.release();
			}
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (!isAlive) {
			finish();
			return;
		}
		mHandler.sendEmptyMessageDelayed(0, 1000L);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		isAlive = false;
		// TODO Auto-generated method stub
		releaseMediaRecorder();
		// 关闭预览并释放资源
		if (camera != null) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}
		super.onPause();
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// 关闭预览并释放资源
		if (camera != null) {
			camera.stopPreview();
			camera.release();
			camera = null;
		}
	}

	/**
	 * 释放recorder资源
	 */
	private void releaseMediaRecorder() {
		if (recorder != null) {
			try {
				recorder.stop();
				recorder.release();
				recorder = null;
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	/**
	 * 开始录像
	 */
	public void recorder() {
		if (!recording) {
			try {
				// 关闭预览并释放资源
				if (camera != null) {
					camera.stopPreview();
					camera.release();
					camera = null;
				}
				if (recorder != null) {
					releaseMediaRecorder();
				}
				recorder = new MediaRecorder();
				// 声明视频文件对象
				myRecVideoFile = new File(filePath);
				if (!myRecVideoFile.exists()) {
					myRecVideoFile.getParentFile().mkdirs();
					myRecVideoFile.createNewFile();
				}
				recorder.reset();
				camera = Camera.open(0);
				// 设置摄像头预览顺时针旋转90度，才能使预览图像显示为正确的，而不是逆时针旋转90度的。
				if (1 == modeCode) {
					Camera.Parameters pa = camera.getParameters();
					List<String> flashList = pa.getSupportedFlashModes();
					if (flashList != null) {
						if (flashList.contains(Parameters.FLASH_MODE_TORCH)) {
							pa.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
							camera.setParameters(pa);
						}
					}
				}
				camera.unlock();
				recorder.setCamera(camera); // 设置摄像头为相机
				recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
				recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
				recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
				// recorder.setVideoSize(320, 240);
				// recorder.setVideoFrameRate(frameRate);
				recorder.setVideoEncodingBitRate(encodingBitRate);
				recorder.setOutputFile(filePath);
				recorder.setPreviewDisplay(mSurfaceHolder.getSurface()); // 预览
				recorder.setMaxFileSize(10 * 1024 * 1024); // 设置视频文件的最大值为10M,单位B
				recorder.setMaxDuration(10 * 1000);// 设置视频的最大时长，单位毫秒
				// recorder.setOrientationHint(90);//视频旋转90度，没有用
				recorder.prepare(); // 准备录像
				recorder.setOnErrorListener(new OnErrorListener() {

					@Override
					public void onError(MediaRecorder mr, int what, int extra) {

					}
				});
				recorder.setOnInfoListener(new OnInfoListener() {

					@Override
					public void onInfo(MediaRecorder mr, int what, int extra) {
						// TODO Auto-generated method stub
					}
				});
				recorder.start(); // 开始录像
				recording = true; // 改变录制状态为正在录制
				mHandler.sendEmptyMessageDelayed(1, Constants.SLEEP_LENGTH);

			} catch (IOException e1) {
				e1.printStackTrace();
				releaseMediaRecorder();
				recording = false;
			} catch (IllegalStateException e) {
				releaseMediaRecorder();
				recording = false;
			}
		}
	}
}
